# -*- coding: utf-8 -*-
"""
API functions
"""
##
# @author J.Ducastel <nospam0@ducastel.name>

# imports
from models import User
from noaccount import settings

# exceptions
class NoUserLogged(Exception):
    """could not perform because there is no user logged"""
    pass

class UserUnsaved(Exception):
    """could not perform an action because User is not saved"""
    pass

class NotAnUser(Exception):
    """expected a User, got something else"""
    pass

class Forbidden(Exception):
    """would break a security rule"""
    pass

from django.http import Http404

class Http403(Exception):
    """will trigger a 403 page in decorators"""
    pass

class Http405(Exception):
    pass

# classes et fonctions

def get_or_create_user(request):
    """
    Get user from session or create and log it in.

    Searches for session-logged user.
    If not found, creates an user and add it to session.
    Uses request.session['na_user'] to store id
    """
    from datetime import timedelta
    if request.session.has_key('na_user'):
        # searching for logged user
        user = User.objects.get(id=request.session['na_user'])
    else:
        # creating it
        if settings.CLOSED_MODE:
            raise Forbidden(u"Automatic user creation forbidden in closed mode")
        user = User.objects.create()
        # log in
        request.session['na_user'] = user.id
        # sets expiry to 1 year
        request.session.set_expiry(timedelta(365))
    return user

def get_user(request):
    """get user from session, if available
    else unsaved user"""
    if request.session.has_key('na_user'):
        # searching for logged user
        return User.objects.get(id=request.session['na_user'])
    else:
        return User()

def log_user_in(request, user):
    """log user in (request and session)"""
    if not isinstance(user, User):
        raise NotAnUser()
    if not user.is_saved():
        raise UserUnsaved()
    request.session['na_user'] = user.id
    request.user = user
    return True

# def register_user(user):


#def register_email_account(request):
#    """
#    creates email account for current user
#
#    if request.method is POST and registering was successful:
#        returns True, EmailAccount, RegisterEmailAccountForm
#    else
#        returns False, None, RegisterEmailAccountForm
#    """